<?php
/*
 * A Twig 1.0 template class to work with PiePHP.
 *
 * @author     Bill Lee <bill@cachecrew.com>
 * @package    PiePHP
 * @since      Version 0.0
 * @copyright  Copyright (c) 2011, Pie Software Foundation
 * @license    http://www.piephp.com/license
 *
 * @see http://www.twig-project.org/doc/templates.html
 */
 
/**
 * If you want to base your project on Twig-based templates, use this controller 
 * for the base-class. 
 * @todo Twig PHP filter probably not needed since the more useful TAG exists.
 */
class TwigController extends Controller {
	/**
	 * Path to Twig installation (w/trailing '/')
	 */
	private static $_twigpath=NULL;
	/**
	 * Twig environment context.
	 */
	private static $_twig;

	private static $_ext='.twig';

	/**
	 * Common initializer called?
	 */
	private static $_init=false;
	private function _sharedInit() {
		global $SITE_DIR;
		
		if (self::$_twigpath === NULL)
			self::$_twigpath = (dirname(dirname(__FILE__)) . '/Twig/');
		require_once self::$_twigpath.'Autoloader.php';
		Twig_Autoloader::register();

		// The following is assumed for all TwigController usage. Might it be 
		// better to make this instance specific?
		$loader = new Twig_Loader_Filesystem($SITE_DIR . 'templates');
		self::$_twig = new Twig_Environment($loader, 
							array('cache' => $SITE_DIR . 'data/cache',
								  'auto_reload' => true));
		self::$_twig->addFilter('php', new Twig_Filter_Function('TwigController::twigPhpFilter'));
		self::$_twig->addTokenParser(new Twig_TokenParserPHP());
		
		self::$_init = true;
	} // _sharedInit()
	
	public function __construct() {
		self::$_init or self::_sharedInit(); // Global init
	} // __construct() 

	/**
	 * Infer a view based on the controller and action, and render that view.
	 * @param  $data: optional data to be passed in to the view.
	 * @param  $templateName: optional template name to override the 
	 *                        controller's default template name.
	 */
	public function render($data = array(), $templateName = NULL) {
		if (!$templateName) {
			$templateName = $this->getViewName();
		}
echo __METHOD__.'#'.__LINE__." $templateName<br/>";

		$template = self::$_twig->loadTemplate($templateName.self::$_ext);
		
		$template->display($data);
	} // render()
	
	/**
	 * Set default extension for templates
	 */
	public function setExt($ext) {
		self::$_ext = $ext[0] == '.' ? $ext : ".$ext";
	}
		
	public static function getTwigPath() {
		return self::$_twigpath;
	} // setPath()
	/**
	 * Set the path to the Doctrine library (the location of the
	 * Doctrine.php file and the Doctrine directory).
	 */
	public static function setTwigPath($path) {
		self::$_twigpath = $path;
	} // setPath()
	
	public static function twigPhpFilter($string) {
		eval($string.';');
	} // twigPhpFilter()
} // class TwigController

